Implementing Inheritance and Its Types in Python
Course: Python Training
Topic: Implementing Inheritance and Its Types
Course Link: Python Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Inheritance in Python
Inheritance is one of the fundamental concepts of object-oriented programming (OOP). It allows a class to acquire attributes and methods from another class. Instead of writing the same code repeatedly, developers can create a parent class containing common functionality and child classes that reuse or extend it.
Python supports inheritance through class definitions. A child class can use inherited methods, introduce new methods, override existing methods, and extend initialization behavior.
Why Is Inheritance Important?
- Promotes code reuse and reduces duplication.
- Organizes related classes into logical hierarchies.
- Allows specialized classes to extend general functionality.
- Supports method overriding and runtime polymorphism.
- Makes larger applications easier to maintain when inheritance relationships are designed carefully.
2. Basic Terminology of Inheritance
| Term |
Meaning |
| Parent class |
The class whose attributes and methods can be inherited by another class. |
| Child class |
The class that inherits from another class. |
| Base class |
Another name for a parent class. |
| Derived class |
Another name for a child class. |
| Method overriding |
Defining a method in a child class with the same name as an inherited method to provide different behavior. |
| super() |
A built-in function commonly used to access methods from the next class in the method resolution order. |
3. Basic Syntax of Inheritance
In Python, a child class specifies its parent class inside parentheses after the class name.
class Parent:
def parent_method(self):
print("This method belongs to the parent class")
class Child(Parent):
def child_method(self):
print("This method belongs to the child class")
obj = Child()
obj.parent_method()
obj.child_method()
Output:
This method belongs to the parent class
This method belongs to the child class
Explanation:
- The
Parent class defines a method named parent_method().
- The
Child class inherits from Parent.
- An instance of
Child can call both its own method and the inherited method.
- The inherited method does not need to be rewritten inside the child class.
4. Types of Inheritance in Python
Inheritance is commonly classified into five types: single, multiple, multilevel, hierarchical, and hybrid inheritance.
| Type |
Description |
Example relationship |
| Single inheritance |
One child class inherits from one parent class. |
Animal → Dog |
| Multiple inheritance |
One child class inherits from two or more parent classes. |
Camera + Phone → SmartPhone |
| Multilevel inheritance |
A class inherits from a child class, creating a chain. |
Animal → Mammal → Dog |
| Hierarchical inheritance |
Multiple child classes inherit from one parent class. |
Animal → Dog and Cat |
| Hybrid inheritance |
A combination of two or more inheritance patterns. |
Multiple and multilevel inheritance combined |
5. Single Inheritance
Single inheritance occurs when one child class inherits from one parent class. It is the simplest and most common form of inheritance.
Example: Animal and Dog
class Animal:
def eat(self):
print("Animals can eat")
class Dog(Animal):
def bark(self):
print("Dog barks")
dog = Dog()
dog.eat()
dog.bark()
Output:
Animals can eat
Dog barks
Explanation: The Dog class inherits the eat() method from Animal and defines its own bark() method.
Advantages of Single Inheritance
- Easy to understand and implement.
- Encourages reuse of common methods.
- Creates a clear relationship between general and specialized classes.
6. Multiple Inheritance
Multiple inheritance occurs when a child class inherits from more than one parent class. Python supports this directly.
Example: Smartphone Features
class Camera:
def take_photo(self):
print("Taking a photo")
class Phone:
def make_call(self):
print("Making a phone call")
class SmartPhone(Camera, Phone):
def browse_internet(self):
print("Browsing the internet")
mobile = SmartPhone()
mobile.take_photo()
mobile.make_call()
mobile.browse_internet()
Output:
Taking a photo
Making a phone call
Browsing the internet
Explanation: The SmartPhone class inherits methods from both Camera and Phone. It also introduces its own functionality.
Advantages and Considerations
- Combines functionality from multiple classes.
- Can represent objects that have several distinct capabilities.
- Requires careful design when parent classes define methods with identical names.
- May create complex method lookup behavior if class relationships are difficult to follow.
7. Multilevel Inheritance
Multilevel inheritance occurs when one class inherits from another child class, creating a chain of inheritance. A class at the bottom of the chain can access eligible inherited functionality from classes higher in the hierarchy.
Example: Animal, Mammal, and Dog
class Animal:
def eat(self):
print("Animal eats food")
class Mammal(Animal):
def walk(self):
print("Mammals can walk")
class Dog(Mammal):
def bark(self):
print("Dog barks")
dog = Dog()
dog.eat()
dog.walk()
dog.bark()
Output:
Animal eats food
Mammals can walk
Dog barks
Explanation:
Animal defines the eat() method.
Mammal inherits from Animal and defines walk().
Dog inherits from Mammal and defines bark().
- A
Dog instance can access methods from all three levels.
8. Hierarchical Inheritance
Hierarchical inheritance occurs when multiple child classes inherit from the same parent class. Each child can reuse the parent's functionality while implementing its own specialized behavior.
Example: Different Animals
class Animal:
def eat(self):
print("Animal eats food")
class Dog(Animal):
def bark(self):
print("Dog barks")
class Cat(Animal):
def meow(self):
print("Cat meows")
dog = Dog()
cat = Cat()
dog.eat()
dog.bark()
cat.eat()
cat.meow()
Output:
Animal eats food
Dog barks
Animal eats food
Cat meows
Explanation: Both Dog and Cat inherit eat() from Animal, but each child class has its own specific method.
Benefits of Hierarchical Inheritance
- Reduces duplicated code across related classes.
- Allows several specialized classes to share common behavior.
- Makes it easier to add new subclasses when they fit the same hierarchy.
9. Hybrid Inheritance
Hybrid inheritance combines two or more inheritance patterns. For example, a class hierarchy may contain both multilevel and multiple inheritance.
Example: Hybrid Inheritance
class Person:
def introduce(self):
print("I am a person")
class Student(Person):
def study(self):
print("I study")
class Employee(Person):
def work(self):
print("I work")
class WorkingStudent(Student, Employee):
def manage_time(self):
print("I balance work and study")
person = WorkingStudent()
person.introduce()
person.study()
person.work()
person.manage_time()
Output:
I am a person
I study
I work
I balance work and study
Explanation:
Student and Employee both inherit from Person.
WorkingStudent inherits from both Student and Employee.
- The resulting structure combines hierarchical and multiple inheritance.
- Both parent paths lead to
Person, so Python's method resolution order determines how inherited methods are looked up.
10. Understanding Method Overriding
Method overriding occurs when a child class defines a method with the same name as a method inherited from its parent class. When the method is called on the child instance, Python generally uses the child's implementation.
Example
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
animal = Animal()
dog = Dog()
animal.sound()
dog.sound()
Output:
Animal makes a sound
Dog barks
Explanation: The Dog class overrides the inherited sound() method. The same method name produces different behavior depending on the object.
Why Is Method Overriding Useful?
- Allows subclasses to customize inherited behavior.
- Supports polymorphism.
- Enables a shared interface for related classes.
- Reduces the need to write separate calling logic for each subtype.
11. Using super() in Inheritance
The super() function provides access to methods from the next class in the method resolution order (MRO). It is commonly used to call a parent initializer or extend an inherited method.
Example: Calling the Parent Initializer
class Person:
def __init__(self, name):
self.name = name
def display(self):
print("Name:", self.name)
class Student(Person):
def __init__(self, name, course):
super().__init__(name)
self.course = course
def display_course(self):
print("Course:", self.course)
student = Student("Amit", "Python")
student.display()
student.display_course()
Output:
Name: Amit
Course: Python
Explanation:
- The
Person initializer sets the name attribute.
- The
Student initializer calls super().__init__(name) to reuse that initialization logic.
- The child initializer sets the additional
course attribute.
- The object can use methods inherited from the parent and defined in the child.
In multiple inheritance, super() follows the method resolution order rather than always meaning a direct call to one specific parent. Cooperative inheritance works best when participating classes use compatible method signatures and call super() consistently.
12. Method Resolution Order (MRO)
The method resolution order determines the order in which Python searches classes for a method or attribute. It is especially important when multiple inheritance is involved.
Example
class A:
def show(self):
print("Class A")
class B(A):
def show(self):
print("Class B")
class C(A):
def show(self):
print("Class C")
class D(B, C):
pass
obj = D()
obj.show()
print(D.mro())
Output for the method call:
Class B
The method lookup starts with D, then follows its MRO, which in this case includes B, C, A, and object. Since B defines show(), Python uses that implementation.
Use ClassName.mro() to inspect the lookup order when debugging inheritance behavior.
13. Inheritance and Constructors
When a child class defines its own __init__(), it does not automatically execute the parent's custom initializer unless it calls it explicitly or otherwise arranges for that initialization. The super() function is a common way to reuse parent initialization.
Example Without Calling the Parent Initializer
class Parent:
def __init__(self):
self.message = "Initialized in Parent"
class Child(Parent):
def __init__(self):
self.child_message = "Initialized in Child"
obj = Child()
print(obj.child_message)
# print(obj.message) # Raises AttributeError
Output:
Initialized in Child
The parent's custom initializer is not executed by the child initializer in this example, so message is not assigned to the instance.
Correct Approach Using super()
class Parent:
def __init__(self):
self.message = "Initialized in Parent"
class Child(Parent):
def __init__(self):
super().__init__()
self.child_message = "Initialized in Child"
obj = Child()
print(obj.message)
print(obj.child_message)
Output:
Initialized in Parent
Initialized in Child
14. Advantages and Disadvantages of Inheritance
| Advantages |
Disadvantages |
| Encourages code reuse. |
Deep hierarchies can become difficult to understand. |
| Organizes related classes. |
Changes in a parent class can affect child classes. |
| Supports method overriding and polymorphism. |
Multiple inheritance can make method lookup more complex. |
| Allows specialized behavior to extend shared functionality. |
Inappropriate inheritance creates tight coupling. |
| Can reduce duplicated implementation. |
Some designs are clearer with composition instead. |
15. Inheritance vs. Composition
Inheritance represents an is-a relationship, while composition represents a has-a relationship. Choosing the correct relationship is important for maintainable object-oriented design.
| Feature |
Inheritance |
Composition |
| Relationship |
Child is a specialized type of parent. |
One object contains or uses another object. |
| Code reuse |
Reuses inherited methods and attributes. |
Reuses functionality through contained objects. |
| Coupling |
Can create a strong dependency on the parent class. |
Often allows components to be changed independently. |
| Example |
Dog inherits from Animal. |
Car has an Engine. |
Example of Composition
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self):
self.engine = Engine()
def start_car(self):
self.engine.start()
print("Car is ready")
car = Car()
car.start_car()
Output:
Engine started
Car is ready
The Car class uses an Engine object rather than inheriting from the Engine class.
16. Best Practices for Implementing Inheritance
- Use inheritance when there is a genuine is-a relationship between classes.
- Keep class hierarchies as simple as possible.
- Use
super() when extending parent initialization or behavior.
- Override methods only when the child needs specialized behavior.
- Keep method names and signatures compatible where polymorphism is expected.
- Understand the method resolution order when using multiple inheritance.
- Avoid duplicating initialization logic across related classes.
- Consider composition when an object needs to use another object without being its subtype.
- Write small examples and tests to verify inherited behavior.
17. Common Errors and Troubleshooting
| Problem |
Possible Cause |
Solution |
| AttributeError |
A required parent initializer was not executed. |
Call super().__init__() when appropriate. |
| TypeError during object creation |
Required initializer arguments are missing or incorrect. |
Check the initializer signature and arguments. |
| Unexpected method output |
A child method overrides the parent method. |
Inspect the class definitions and MRO. |
| Duplicate logic |
Common behavior is repeatedly implemented in subclasses. |
Move genuinely shared behavior into a suitable parent class. |
| Complex multiple inheritance |
Parent classes define overlapping methods or incompatible initializers. |
Review the MRO and use cooperative super() calls where appropriate. |
| Incorrect class relationship |
Inheritance is used only to reuse unrelated functionality. |
Consider composition or a standalone helper class. |
18. Practice Exercises
Exercise 1: Single Inheritance
Create a Vehicle parent class with a method named start(). Create a Car child class with a method named drive(). Demonstrate both methods.
Exercise 2: Multiple Inheritance
Create two classes, Camera and MusicPlayer. Define a SmartDevice class that inherits from both and provides an additional method.
Exercise 3: Multilevel Inheritance
Create a hierarchy consisting of Person, Employee, and Manager. Add a distinct method to each class and call all three from a manager object.
Exercise 4: Hierarchical Inheritance
Create a parent class named Shape and child classes named Circle and Rectangle. Give both child classes their own area-calculation methods.
Exercise 5: Method Overriding
Create an Animal class with a sound() method. Override it in Dog and Cat to display different sounds.
Exercise 6: Constructor Inheritance
Create a Person class that initializes a name and an Employee subclass that initializes a name and employee ID. Use super() to reuse the parent initializer.
Exercise 7: Mini Project — Employee Management
Build an employee management program with a common Employee class and specialized subclasses such as Developer, Designer, and Manager. Store shared employee details in the parent class and implement role-specific methods in the child classes.
19. Interview Questions and Answers
Q1. What is inheritance in Python?
Answer: Inheritance is an OOP feature that allows a class to reuse and extend the attributes and methods of another class.
Q2. What are the five common types of inheritance?
Answer: Single, multiple, multilevel, hierarchical, and hybrid inheritance.
Q3. Does Python support multiple inheritance?
Answer: Yes. A class can inherit from more than one parent class.
Q4. What is method overriding?
Answer: It is the process of defining a method in a child class with the same name as an inherited method to provide specialized behavior.
Q5. What is the purpose of super()?
Answer: It provides access to methods in the next class in the method resolution order, commonly to reuse parent initialization or behavior.
Q6. What is multilevel inheritance?
Answer: It occurs when inheritance forms a chain, such as Animal, Mammal, and Dog.
Q7. What is hierarchical inheritance?
Answer: It occurs when multiple child classes inherit from the same parent class.
Q8. What is hybrid inheritance?
Answer: It combines multiple inheritance patterns within a class hierarchy.
Q9. What is method resolution order?
Answer: MRO determines the order in which Python searches classes for inherited methods and attributes.
Q10. What is the difference between inheritance and composition?
Answer: Inheritance models an is-a relationship, while composition models a has-a relationship in which an object contains or uses another object.
20. Quick Revision Checklist
- Inheritance enables code reuse and specialization.
- The parent class provides shared functionality.
- The child class can add or override methods.
- Single inheritance has one parent class.
- Multiple inheritance has two or more parent classes.
- Multilevel inheritance forms an inheritance chain.
- Hierarchical inheritance has multiple children sharing one parent.
- Hybrid inheritance combines inheritance patterns.
super() follows the method resolution order.
- MRO is particularly important in multiple inheritance.
- Composition is often preferable when the relationship is has-a rather than is-a.
21. Conclusion
Inheritance is a powerful Python OOP feature that helps developers build reusable, organized, and extensible applications. Understanding single, multiple, multilevel, hierarchical, and hybrid inheritance makes it easier to model relationships between classes.
By practicing method overriding, constructor inheritance, super(), and method resolution order, you can develop a stronger understanding of how Python classes work together. Always choose inheritance relationships carefully and consider composition when it provides a simpler design.
Learn Python with JustAcademy
Strengthen your Python programming skills with structured learning, hands-on examples, and object-oriented programming practice.
Python Training Course: Explore Python Training
Course Demo: Register for a Course Demo
JustAcademy Website: Visit JustAcademy